package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class DtsStorageServiceImpl implements DtsStorageService {

    @Autowired
    DtsStorageMapper storageMapper;


    @Override
    public IPage<DtsStorage> queryPage(Integer page, Integer limit, String sort, String order, String key, String name) {

        IPage<DtsStorage> iPage = new Page<>(page,limit);

        QueryWrapper<DtsStorage> qw = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            qw.like("`key`",key);
        }
        if(!StringUtils.isEmpty(name)){
            qw.like("name",name);
        }
        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)){
            if(order.equalsIgnoreCase("desc")){
                qw.orderByDesc(sort);
            }else {
                qw.orderByAsc(sort);
            }
        }

        storageMapper.selectPage(iPage,qw);

        return iPage;
    }

    @Value("${aliyun.oss.endpoint}")
    String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    String bucketName;

    @Override
    public DtsStorage insert(String name,String key,Integer size,byte[] bytes,String type) throws Exception {
        //分两步，一步是上传到阿里云OSS一步是添加到数据库
        String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, key, bytes);

        DtsStorage dtsStorage = new DtsStorage();
        dtsStorage.setAddTime(new Date());
        dtsStorage.setUpdateTime(new Date());
        dtsStorage.setKey(key);
        dtsStorage.setName(name);
        dtsStorage.setDeleted(false);
        dtsStorage.setSize(size);
        dtsStorage.setUrl(url);
        dtsStorage.setType(type);
        storageMapper.insert(dtsStorage);
        return dtsStorage;
    }

    @Override
    public DtsStorage update(DtsStorage storage) {
        storage.setUpdateTime(new Date());
        storageMapper.updateById(storage);
        return storage;
    }

    @Override
    public void delete(DtsStorage storage) {
        storageMapper.deleteById(storage);
        AliyunOSSUtil.deleteFile(endpoint,accessKeyId,accessKeySecret,bucketName,storage.getKey());
    }
}
